package com.caiyouxi.user.util;

import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.codec.binary.StringUtils;
import org.nutz.lang.Encoding;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static org.apache.commons.codec.binary.Base64.decodeBase64;
import static org.apache.commons.codec.binary.Base64.encodeBase64String;

/**
 * Created by Administrator on 2017/11/11.
 */
public class Util {

    protected static final Log log = Logs.get();

    /**
     * 判断请求时间戳是否超时（200秒）
     *
     * @param ts
     * @return
     */
    public static Boolean isTimestampTimedOut(long ts) {

        if (Lang.isEmpty(ts)) {
            return true;
        } else {
            if (Instant.now().getEpochSecond() - ts >= 200) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 手机号码转手机邮箱
     *
     * @param phone
     * @return
     */
    public static String phone2Email(String phone) {

        String number = Strings.isMobile(phone) ? phone.substring(0, 3) : "";

        switch (number) {
            case "134":
                return phone + "@139.com";
            case "135":
                return phone + "@139.com";
            case "136":
                return phone + "@139.com";
            case "137":
                return phone + "@139.com";
            case "138":
                return phone + "@139.com";
            case "139":
                return phone + "@139.com";
            case "150":
                return phone + "@139.com";
            case "151":
                return phone + "@139.com";
            case "152":
                return phone + "@139.com";
            case "157":
                return phone + "@139.com";
            case "158":
                return phone + "@139.com";
            case "159":
                return phone + "@139.com";
            case "182":
                return phone + "@139.com";
            case "183":
                return phone + "@139.com";
            case "184":
                return phone + "@139.com";
            case "187":
                return phone + "@139.com";
            case "178":
                return phone + "@139.com";
            case "188":
                return phone + "@139.com";
            case "147":
                return phone + "@139.com";
            case "130":
                return phone + "@wo.cn";
            case "131":
                return phone + "@wo.cn";
            case "132":
                return phone + "@wo.cn";
            case "145":
                return phone + "@wo.cn";
            case "155":
                return phone + "@wo.cn";
            case "156":
                return phone + "@wo.cn";
            case "176":
                return phone + "@wo.cn";
            case "185":
                return phone + "@wo.cn";
            case "186":
                return phone + "@wo.cn";
            case "133":
                return phone + "@189.cn";
            case "153":
                return phone + "@189.cn";
            case "177":
                return phone + "@189.cn";
            case "180":
                return phone + "@189.cn";
            case "181":
                return phone + "@189.cn";
            case "189":
                return phone + "@189.cn";
            default:
                return null;
        }
    }

    public static long calculateIntervalTime(Date endTime, Date startTime) {
        return endTime.getTime() - startTime.getTime();
    }

    /**
     * 地球半径
     */
    private static final double EARTH_RADIUS = 6378137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 根据两点间经纬度坐标（double值），计算两点间距离，单位为米
     *
     * @param lng1
     * @param lat1
     * @param lng2
     * @param lat2
     * @return
     */
    public static double getDistance(double lng1, double lat1, double lng2, double lat2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    /**
     * 取Json字段值
     *
     * @param jsonStr   JSON
     * @param field     取值字段
     * @param tailField 后一个字段 取值字段为结束字段填"}"
     * @return
     */
    public static String getValueFromJson(String jsonStr, String field,
                                          String tailField) {
        if (Strings.isBlank(jsonStr.trim())
                || Strings.isBlank(field.trim())
                || Strings.isBlank(tailField.trim()))
            return null;
        else {
            jsonStr = jsonStr.replaceAll("\"", "").trim();
            return Strings.removeFirst(jsonStr.substring(
                    jsonStr.indexOf(field) + field.length() + 1,
                    jsonStr.indexOf(tailField)).replaceAll(",", ""), ':').trim();
        }
    }


    public static Double l2d(long l) {

        return Double.parseDouble(l + "");
    }

    public static Map<String, Object> buildNiceue(String error) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> resp = new HashMap<>();
        if (Lang.isEmpty(error)) {
            map.put("ok", "");
            resp.put("data", map);
            return resp;
        } else {
            map.put("error", error);
            resp.put("data", map);
            return resp;
        }
    }

    public static class Url {

        public static String encode(String s) {

            if (Strings.isBlank(s)) {
                return "";
            } else {
                try {
                    return URLEncoder.encode(s, Encoding.UTF8);
                } catch (UnsupportedEncodingException e) {
                    log.error(e.getMessage());
                    return "";
                }
            }
        }

        public static String decode(String s) {

            if (Strings.isBlank(s)) {
                return "";
            } else {
                try {
                    return URLDecoder.decode(s, Encoding.UTF8);
                } catch (UnsupportedEncodingException e) {
                    log.error(e.getMessage());
                    return "";
                }
            }
        }
    }

    public static class Base64 {

        public static String encode(String s) {

            if (Strings.isBlank(s)) {
                return "";
            } else {
                return encodeBase64String(s.getBytes(Encoding.CHARSET_UTF8));
            }
        }

        public static String decode(String s) {
            if (Strings.isBlank(s)) {
                return "";
            } else {
                return StringUtils.newStringUtf8(decodeBase64(s));
            }
        }
    }

    public static String getAgent(HttpServletRequest request) {

        if (!Lang.isEmpty(request)) {
            UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
            return "操作系统版本（" + userAgent.getOperatingSystem() + "）；浏览器版本（" + userAgent.getBrowser() + "-" + userAgent.getBrowserVersion() + "）";
        } else {
            return "";
        }
    }


}
